<template>
  <el-card class="sku-card">
    <el-form label-width="100px" ref="skuFromRef" :model="skuFromDate" :rules="skuFromRules">
      <el-form-item label="SPU名称">{{ spu.spuName }}</el-form-item>
      <el-form-item label="SKU名称" prop="skuName">
        <el-input placeholder="SkU名称" v-model="skuFromDate.skuName" />
      </el-form-item>
      <el-form-item label="价格(元)" prop="price">
        <el-input-number v-model="skuFromDate.price" class="sku-input-number" :min="0" :max="10" controls-position="right" placeholder="请输入价格" />
      </el-form-item>
      <el-form-item label="重量(kg)" prop="weight">
        <el-input-number
          v-model="skuFromDate.weight"
          class="sku-input-number"
          :min="0"
          :max="10"
          controls-position="right"
          placeholder="请输入价格"
        />
      </el-form-item>
      <el-form-item label="规格描述" prop="skuDesc">
        <el-input placeholder="规格描述" :rows="2" type="textarea" v-model="skuFromDate.skuDesc" />
      </el-form-item>

      <el-form-item label="平台属性" prop="skuAttrValueList">
        <el-row :gutter="10" class="sku-wrap">
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" v-for="(saleAttr, index) in attrList" :key="saleAttr.id">
            <div class="sku-attr-wrap">
              <span class="sku-attr-name">{{ saleAttr.attrName }}</span>
              <el-select v-model="skuFromDate.skuAttrValueList[index]">
                <el-option
                  v-for="attrValue in saleAttr.attrValueList"
                  :key="attrValue.id"
                  :label="attrValue.valueName"
                  :value="`${saleAttr.id}:${saleAttr.attrName}:${attrValue.id}:${attrValue.valueName}`"
                />
              </el-select>
            </div>
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item label="销售属性" prop="skuSaleAttrValueList">
        <el-row :gutter="10" class="sku-wrap">
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" v-for="(attr, index) in spuSaleAttr" :key="attr.id">
            <div class="sku-attr-wrap">
              <span class="sku-attr-name">{{ attr.saleAttrName }}</span>
              <el-select v-model="skuFromDate.skuSaleAttrValueList[index]">
                <el-option
                  v-for="attrValue in attr.spuSaleAttrValueList"
                  :key="attrValue.id"
                  :label="attrValue.saleAttrValueName"
                  :value="`${attr.id}:${attr.saleAttrName}:${attrValue.id}:${attrValue.saleAttrValueName}`"
                />
              </el-select>
            </div>
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item label="图片列表" prop="skuImageList">
        <el-table :data="spuImageList" border @selection-change="handleSelectionChange">
          <el-table-column type="selection" />
          <el-table-column label="图片">
            <template v-slot="{ row }">
              <img :src="row.imgUrl" :alt="row.imgName" class="sku-img" />
            </template>
          </el-table-column>
          <el-table-column label="名称" prop="imgName"></el-table-column>
          <el-table-column label="操作">
            <template v-slot="{ row }">
              <el-tag type="success" size="small" v-if="row.isDefault === '1'"> 默认 </el-tag>
              <el-button type="primary" size="small" v-else @click="setDefaultImg(row)"> 设置默认 </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm">保存</el-button>
        <el-button>取消</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script lang="ts">
export default {
  name: "SaveSku",
};
</script>

<script lang="ts" setup>
import type { spuFormDateType, spuSaleAttrList, SpuImageList } from "@/api/product/model/spuModel";
import { getSpuSaleAttrListApi, getSpuImageListApi } from "@/api/product/spu";
import { useCategoryStore } from "@/stores/category";
import type { AttrList } from "@/api/product/model/attrModel";
import { onMounted, ref, reactive } from "vue";
import { getAttrListApi } from "@/api/product/attr";
import type { FormInstance, FormRules } from "element-plus";
import { saveSkuApi } from "@/api/product/sku";
const props = defineProps<{
  spu: spuFormDateType;
}>();
const categoryStore = useCategoryStore();

const attrList = ref<AttrList>([]); //属性列表
const spuSaleAttr = ref<spuSaleAttrList>([]); //spu销售属性
const spuImageList = ref<SpuImageList>([]); //spu图片列表

onMounted(async () => {
  const { category1Id, category2Id, category3Id } = categoryStore;
  attrList.value = await getAttrListApi({
    category1Id: category1Id as number,
    category2Id: category2Id as number,
    category3Id: category3Id as number,
  });
});
onMounted(async () => {
  spuSaleAttr.value = await getSpuSaleAttrListApi(props.spu.id as number);
});

onMounted(async () => {
  spuImageList.value = await getSpuImageListApi(props.spu.id as number);
});

//收集表单数据
const skuFromRef = ref<FormInstance>();
const skuFromDate = reactive({
  skuName: "",
  price: 0,
  weight: 0,
  skuDesc: "",
  skuAttrValueList: [],
  skuSaleAttrValueList: [],
  skuImageList: [
    // {
    //   imgName: "string",
    //   imgUrl: "string",
    //   isDefault: "string",
    // },
  ],
  skuDefaultImg: "",
});

const skuImageListValidator = (rule: any, value: any, callback: any) => {
  if (!value.length) {
    callback("请至少选择一张图片");
    return;
  }

  if (!skuFromDate.skuDefaultImg) {
    callback("请至少选择一张默认图片");
    return;
  }

  callback();
};
const skuFromRules = reactive<FormRules>({
  skuName: [{ required: true, message: "请输入SKU名称", trigger: "blur" }],
  price: [{ required: true, message: "请输入SKU价格", trigger: "blur" }],
  weight: [{ required: true, message: "请输入SKU重量", trigger: "blur" }],
  skuDesc: [{ required: true, message: "请输入SKU规则描述", trigger: "blur" }],
  skuAttrValueList: [{ required: true, message: "请选择SKU平台属性" }],
  skuSaleAttrValueList: [{ required: true, message: "请选择SKU销售属性" }],
  skuImageList: [{ required: true, validator: skuImageListValidator }],
});
// 收集图片数据
const handleSelectionChange = (val: any) => {
  skuFromDate.skuImageList = val;
};
//默认图片
const setDefaultImg = (row: any) => {
  spuImageList.value.forEach((img) => {
    img.isDefault = "0";
  });
  row.isDefault = "1";
  if (!skuFromDate.skuDefaultImg) {
    skuFromRef.value?.clearValidate(["skuImageList"]);
  }
  skuFromDate.skuDefaultImg = row.imgUrl;
};
//提交表单
const submitForm = async () => {
  await skuFromRef.value?.validate();
  saveSkuApi({
    ...skuFromDate,
    skuSaleAttrValueList: skuFromDate.skuSaleAttrValueList
      .filter(Boolean)
      .map((attr:any) => {
        console.log(typeof attr,attr)
        const [saleAttrId, saleAttrName, saleAttrValueId, saleAttrValueName] =
          attr.split(":");
        return {
          saleAttrId: +saleAttrId, // 销售属性id
          saleAttrName, // 销售属性名称
          saleAttrValueId: +saleAttrValueId, // 销售属性值id
          saleAttrValueName, // 销售属性值名称
        };
      }),
    skuAttrValueList: skuFromDate.skuAttrValueList
      .filter(Boolean)
      .map((attr:any) => {
        const [attrId, attrName, valueId, valueName] = attr.split(":");
        return {
          attrId: +attrId, // 属性id
          attrName, // 属性名
          valueId: +valueId, // 属性值id
          valueName, // 属性值名称
        };
      }),
    spuId: props.spu.id,
    category3Id: categoryStore.category3Id,
  });
};
</script>

<style scoped>
.sku-input-number,
.sku-wrap {
  width: 100%;
}
.sku-card {
  margin: 20px 0;
  /* &:deep() {
    .el-input-number .el-input__inner  {
      text-align: left;
    }
  } */
}

.sku-card:deep(.el-input-number .el-input__inner) {
  text-align: left;
}

.sku-attr-name {
  margin-right: 10px;
  white-space: nowrap;
}

.sku-img {
  width: 200px;
  height: 100px;
}

.sku-attr-wrap {
  margin-bottom: 10px;
  display: flex;
}
</style>
